package com.tentative.competition.common.utils.file;

import com.tentative.competition.common.model.schedule.vo.FileVo;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 文件压缩工具类
 * @author SmileH
 */
public class FileCompressUtils {

    /**
     * 文件压缩导出
     * @param fileList 文件对象
     * @param fileName 文件名称
     */
    public static void downTogetherAndZip(List<FileVo> fileList, String fileName) {
        HttpServletResponse resp = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        resp.setContentType("application/octet-stream");
        //暂时设定压缩下载后的文件名字为test.zip
        resp.setHeader("Content-Disposition", "attachment;filename="+fileName+".zip");
        resp.setCharacterEncoding("UTF-8");
        try {
            ZipOutputStream zos = new ZipOutputStream(resp.getOutputStream());
            for (FileVo vo : fileList) {
                File file = new File(vo.getFileUrl());
                zos.putNextEntry(new ZipEntry(vo.getFileName()));
                FileInputStream fis = new FileInputStream(file);
                byte b[] = new byte[1024];
                int n = 0;
                while ((n = fis.read(b)) != -1) {
                    zos.write(b, 0, n);
                }
                zos.flush();
                fis.close();
            }
            //设置解压文件后的注释内容
            zos.flush();
            zos.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
